package com.sample.service.impl;

import java.util.List;

import javax.annotation.Resource;

import com.trg.dao.dao.original.DAODispatcher;
import com.trg.search.flex.FlexSearch;
import com.trg.search.flex.FlexSearchWrapper;
import com.trg.search.SearchResult;

public class EntityServiceImpl {

	private DAODispatcher dao;
	
	@Resource(name="DAODispatcher")
	public void setDAODispatcher(DAODispatcher daoDispatcher) {
		this.dao = daoDispatcher;
	}
	
	
	public Object create(Object entity) {
		dao.create(entity);
		return entity;
	}

	public Object createOrUpdate(Object entity) {
		dao.createOrUpdate(entity);
		return entity;
	}

	public void deleteById(String className, Long id) throws ClassNotFoundException {
		dao.deleteById(Class.forName(className), id);
	}

	public void deleteEntity(Object entity) {
		dao.deleteEntity(entity);
	}
	
	public void deleteListById(String className, Long[] ids) throws ClassNotFoundException {
		if (ids == null)
			return;
		Class<?> klass = Class.forName(className);
		for (Long id : ids) {
			if (id != null)
				dao.deleteById(klass, id);
		}
	}
	
	public void deleteList(Object[] entities) {
		if (entities == null)
			return;
		for (Object entity : entities) {
			if (entity != null)
				dao.deleteEntity(entity);
		}
	}

	public Object fetch(String className, Long id) throws ClassNotFoundException {
		return dao.fetch(Class.forName(className), id);
	}

	public List<?> fetchAll(String className) throws ClassNotFoundException {
		return dao.fetchAll(Class.forName(className));
	}

	public Object update(Object entity) {
		dao.update(entity);
		return entity;
	}

	public List<?> search(FlexSearch options) {
		return dao.search(new FlexSearchWrapper(options));
	}
	
	public int count(FlexSearch options) {
		return dao.count(new FlexSearchWrapper(options));
	}

	public SearchResult<?> searchAndCount(FlexSearch options) {
		return dao.searchAndCount(new FlexSearchWrapper(options));
	}
}
